package XynLeen.GraduationProject.Activities;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.TimePickerView;
import com.youth.xframe.widget.XToast;

import org.litepal.crud.DataSupport;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import XynLeen.GraduationProject.Adapter.MyFragmentPagerAdapter;
import XynLeen.GraduationProject.Bean.BudgetBean;
import XynLeen.GraduationProject.Fragments.Bills.Fragment_In;
import XynLeen.GraduationProject.Fragments.Bills.Fragment_Out;
import XynLeen.GraduationProject.R;
import XynLeen.GraduationProject.view.BaseActivity;
import XynLeen.GraduationProject.view.EditLineItem;
import XynLeen.GraduationProject.view.TitleArrowLineItem;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class Activity_Bills_Add extends BaseActivity {

    SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    @Bind(R.id.money)
    EditLineItem mCost;
    @Bind(R.id.remark)
    EditLineItem mRemark;
    @Bind(R.id.time)
    TitleArrowLineItem mTime;
    @Bind(R.id.add)
    Button mAdd;
    @Bind(R.id.ib_navigation_back)
    ImageButton mIbNavigation_back;
    @Bind(R.id.ib_navigation_del)
    ImageButton mIbNavigation_del;
    @Bind(R.id.tv_navigation_label)
    TextView mTvNavigation;

    BudgetBean mBudget;

    private TabLayout mTabLayout;
    private ViewPager mViewPager;
    private MyFragmentPagerAdapter myFragmentPagerAdapter;
    private TabLayout.Tab one;
    private TabLayout.Tab two;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);

        initViews();

        mIbNavigation_del.setVisibility(View.INVISIBLE);

        mBudget = (BudgetBean) getIntent().getSerializableExtra("bean");
        String date = getIntent().getStringExtra("date");
        if (!TextUtils.isEmpty(date)) {
            mTime.setEnabled(false);
            mTime.setDetail(date + " 00:00");
        }
        if (mBudget != null) {
            setData(mBudget);
            //显示删除键
            mIbNavigation_del.setVisibility(View.VISIBLE);
        }
        mTime.setDetail(formatter1.format(new Date()));
    }

    private void setData(BudgetBean work) {
        mCost.setContent(mBudget.getCost());
        mRemark.setContent(mBudget.getRemark());
        mTime.setDetail(mBudget.getDate());

        mAdd.setText("修改");
    }

    @OnClick(R.id.time)
    public void time(View view) {
        // 隐藏软键盘
        ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE))
                .hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        //时间选择器
        TimePickerView pvTime = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                mTime.setDetail((formatter1.format(date) + ""));
            }
        }).setType(new boolean[]{true, true, true, true, true, false})// 默认全部显示
                .build();
        pvTime.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
        pvTime.show();
    }

    @OnClick(R.id.add)
    public void add() {

        if (TextUtils.isEmpty(mCost.getContent())) {
            XToast.error("金额不能为空");
            return;
        }

        String mNumber=mCost.getContent();
        Pattern pattern = Pattern.compile("-?[0-9]+.?[0-9]+");
        Matcher isNum = pattern.matcher(mNumber);
        if( !isNum.matches() ){
            XToast.error("输入有误，请检查金额输入格式");
            return;
        }

        if (TextUtils.isEmpty(mTime.getTextViewVal())) {
            XToast.error("时间不能为空");
            return;
        }

        int imgId;
        String curName;
        int imgId_test=1;
        String curName_test="aa";
        int one=mTabLayout.getSelectedTabPosition();
        if(one==0){
            imgId_test=Fragment_Out.curImgId;
            curName_test=Fragment_Out.curName;
            }else if(one==1){
                imgId_test=Fragment_In.curImgId;
                curName_test=Fragment_In.curName;
            }
        imgId=imgId_test;
        curName=curName_test;

        BudgetBean bean = new BudgetBean();
        if(one==0){
            bean.setCost("-"+mCost.getContent());
        }else if(one==1){
            bean.setCost(mCost.getContent());
        }

        bean.setRemark(mRemark.getContent());
        bean.setDate(mTime.getTextViewVal());
        bean.setImage(imgId);
        bean.setType(curName);

        if (curName==null){
            XToast.error("请选择一项分类");
            return;
        }

        if (mBudget != null) {
            bean.update(mBudget.getId());
        } else {
            bean.save();
        }
        finish();
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_bills_add;
    }

    @Override
    public void initData(Bundle savedInstanceState) {

    }

    @Override
    public void initView() {

    }


    @OnClick({R.id.ib_navigation_back,R.id.ib_navigation_del})
    public void OnClick(View v){
        switch (v.getId()){
            case R.id.ib_navigation_back:
                finish();
                break;
            case R.id.ib_navigation_del:
                final AlertDialog dialog = new AlertDialog.Builder(this)
                        .setTitle("提示")//设置对话框的标题
                        .setMessage("确定删除吗？")//设置对话框的内容
                        //设置对话框的按钮
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        })
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                DataSupport.delete(BudgetBean.class, mBudget.getId());
                                finish();
                                dialog.dismiss();
                            }
                        }).create();

                dialog.show();
                break;
        }
    }

    private void initViews() {

        //使用适配器将ViewPager与Fragment绑定在一起
        mViewPager= (ViewPager) findViewById(R.id.viewPager);
        mViewPager.setAdapter(new MyFragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int i) {
                Fragment fragment = null;
                switch (i) {
                    case 0:
                        fragment = new Fragment_Out();
                        int imgId;
                        String curName;
                        imgId=Fragment_In.curImgId;
                        curName=Fragment_In.curName;
                        break;
                    case 1:
                        fragment = new Fragment_In();
                        int imgId1;
                        String curName1;
                        imgId1=Fragment_In.curImgId;
                        curName1=Fragment_In.curName;
                        break;
                    default:
                        break;
                }

                return fragment;
            }

            @Override
            public int getCount() {
                return 2;
            }
        });

        //将TabLayout与ViewPager绑定在一起
        mTabLayout = (TabLayout) findViewById(R.id.tabLayout);
        mTabLayout.setupWithViewPager(mViewPager);

        //指定Tab的位置
        one = mTabLayout.getTabAt(0);
        two = mTabLayout.getTabAt(1);

        //设置Tab的图标，假如不需要则把下面的代码删去
//        one.setIcon(R.mipmap.ic_launcher);
//        two.setIcon(R.mipmap.ic_launcher);

    }

//
//    @Override
//    public void onClick(View v) {
//        switch (v.getId()){
//            case R.id.ib_navigation_back:
//                startActivity(new Intent(Activity_Bills_Add.this, Activity_Bills.class));
//                finish();
//                break;
//            case R.id.bt_add_submit:
//                String cost = mEtMoney.getText().toString();
//                String remark = mEtRemark.getText().toString();
//                String date = mTvDate.getText().toString();
//                String tag = String.valueOf(System.currentTimeMillis());
//                int imgId;
//                String curName;
//                int imgId_test=1;
//                String curName_test="aa";
//
//                int one=mTabLayout.getSelectedTabPosition();
//                //Log.e("oneone","下标"+one);
//                if(one==0){
//                    imgId_test=Fragment_Out.curImgId;
//                    curName_test=Fragment_Out.curName;
//                }else if(one==1){
//                    imgId_test=Fragment_In.curImgId;
//                    curName_test=Fragment_In.curName;
//                }
//                imgId=imgId_test;
//                curName=curName_test;
//
//                if (!cost.equals("")) {
//                    //添加数据
//                    SQLiteDatabase db = mHelper.getWritableDatabase();
//                    ContentValues values = new ContentValues();
//                    values.put("image",imgId);
//                    values.put("type",curName);
//                    values.put("cost", cost);
//                    values.put("date", date);
//                    values.put("remark", remark);
//                    values.put("tag", tag);
//                    db.insert("Bill", null, values);
//                    Log.e("savedata","存进去了！");
//                    values.clear();
//                }
//
//                startActivity(new Intent(Activity_Bills_Add.this, Activity_Bills.class));
//                finish();
//                break;
//            case R.id.tv_datepicker:
//                // 日期格式为yyyy-MM-dd
//                mDatePicker.show(mTvDate.getText().toString());
//                Log.e("pickershow", "css");
//                break;
//        }
//    }
//
//    @Override
//    protected void onDestroy() {
//        super.onDestroy();
//        mDatePicker.onDestroy();
//    }
//
//    private void initDatePicker() {
//        long beginTimestamp = DateFormatUtils.str2Long("2009-05-01", false);
//        long endTimestamp = System.currentTimeMillis();
//
//        mTvDate.setText(DateFormatUtils.long2Str(endTimestamp, false));
//
//        // 通过时间戳初始化日期，毫秒级别
//        mDatePicker = new CustomDatePicker(this, new CustomDatePicker.Callback() {
//            @Override
//            public void onTimeSelected(long timestamp) {
//                mTvDate.setText(DateFormatUtils.long2Str(timestamp, false));
//            }
//        }, beginTimestamp, endTimestamp);
//
//        // 不允许点击屏幕或物理返回键关闭
//        mDatePicker.setCancelable(false);
//        // 不显示时和分
//        mDatePicker.setCanShowPreciseTime(false);
//        // 不允许循环滚动
//        mDatePicker.setScrollLoop(false);
//        // 不允许滚动动画
//        mDatePicker.setCanShowAnim(false);
//    }
//
//    //输入金额焦点改变
//    @Override
//    public void onFocusChange(View v, boolean hasFocus) {
//        int id = v.getId();
//
//        if (id == R.id.et_money) {
//            if (hasFocus) {
//                mEtMoney.setActivated(true);
//            }
//        } else {
//            if (hasFocus) {
//                mEtMoney.setActivated(false);
//            }
//        }
//    }
//
//    @Override
//    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//
//    }
//
//    @Override
//    public void onTextChanged(CharSequence s, int start, int before, int count) {
//        String money = mEtMoney.getText().toString().trim();
//
//        //提交按钮是否可用
//        if (!TextUtils.isEmpty(money)) {
//            mBtSubmit.setBackgroundResource(R.drawable.login_submit);
//            mBtSubmit.setTextColor(getResources().getColor(R.color.white));
//            mBtSubmit.setEnabled(true);
//        } else {
//            mBtSubmit.setBackgroundResource(R.drawable.login_submit_lock);
//            mBtSubmit.setTextColor(getResources().getColor(R.color.account_lock_font_color));
//            mBtSubmit.setEnabled(false);
//        }
//
//    }
//
//    @Override
//    public void afterTextChanged(Editable s) {
//
//    }
}
